<template>
  <view>
    <view class="header-con">
      <view class="header-tab">
        <tabs ref="tabsRef" :list="tablist" @tabItemClick="tabSelect" marright="70rpx" activeWeight='700'
          :current="currentIndex" fontSize="32rpx" barMargin="10" activeColor="#000" activeBarColor="#53A87F"></tabs>
        <!-- <text :class="{active: activeTab === index }" v-for="(item,index) in tabData" :key="index" @click="handleTabClick(index)">{{ item.text }}</text> -->
      </view>
    </view>
    <view class="coupon-con" style="height: calc(100vh - 87rpx);" :class="{emptyActives:loadedList&&ouponsList.length<=0}">
     
      <!-- <view class="cu-bar-flex-left" v-for="(item,index) in seletDelivery" @tap="seleData(index,id)" :class="{ active: item.status }" :key="item.id">
					<text>{{item.name}}</text>
					<view v-if="item.status" class="icon"><text style="color: #53A87F;" class="text-gray cuIcon-check"></text></view>
			   </view> -->
      <scroll-view class="uni-bar-wbg" style="height:100%" scroll-y scroll-with-animation refresher-enabled="true"
        :refresher-triggered="refLoad" @refresherrefresh="refresherrefresh" @scrolltolower="scrolltolower">
        <empty positions="absolute" :empty="loadedList&&ouponsList.length<=0" :zIndexs="100"
          :imgUrl="'https://cdn-static.yekjx.com/'+'food/empty/images/empty_ico04.png'" content="暂无VIP专区券"></empty>
        <view class="cu-bar-yhj p_rlt" v-for="item in ouponsList" :key="item.id">
          <view v-if="item.status==142 && item.is_gif=='5' && item.channel" class="sr_box point"
            @click.stop="sendItem(item)">
            我要送人
          </view>
          <text v-if="item.status==1132 && item.is_gif=='5'" class="cu-bar-invalid">已赠送</text>
          <text v-if="item.status == '141'" class="cu-bar-invalid">已过期</text>
          <view class="cu-bar-invalid" v-if="item.status=='146'">已使用</view>
          <view class="cu-bar-yhj-left">
            <view class="cu-bar-yhj-Pic"
              :style="{ background: item.status !== '142' || !item.channel ? 'rgba(153, 153, 153, 0.10)' : '' }">
              <!-- <view class="cu-bar-yhj-PicStyle">{{ item.money }}<text v-if="!item.type"
                            class="cu-bar-yhj-PicZk">折</text><text v-else="item.type"
                            class="cu-bar-yhj-PicZk">元</text></view> -->
              <view class="cu-bar-yhj-PicStyle" :style="{color:item.status=='142' && item.channel ?'':'#999'}">
                {{ item.coupon_money}}<text class="price_text">元</text></view>
              <!-- <view v-if="item.type && item.content" class="cu-bar-yhj-min">
                          <text>满{{ item.content }}可用</text></view> -->
              <view class="text-center">
                <view v-if="item.status=='142' && item.channel" class="d_ib actbox text-white" @click="tapToUse(item)">
                  去使用
                </view>
              </view>
            </view>
            <view class="cu-bar-yhj-left-text">
              <text class="cu-bar-yhj-title"
                :style="{color:item.status=='142' && item.channel ?'':'#999'}">VIP专区券</text>
              <view class="flex justify-between align-center">
                <text class="cu-bar-yhj-left-time"
                  :style="{color:item.status=='142' && item.channel ?'':'#999'}">有效期至{{ item.endTime }}</text>
                <!-- <view class="cu-bar-yhj-right">
                            <text v-if="!item.invalid" class="cu-bar-yhj-rightBtn"
                              :class="{'gray-element':item.invalid,'alreadyClass':item.statue ===2}">{{item.statue === 2 ? '已使用' : '去使用'}}</text>
                            
                          </view> -->
                <!-- <text v-if="item.invalid" class="cu-bar-invalid">已失效</text> -->
              </view>
              <view class="">
                <view class="flex justify-between align-center" :class="{justiftRight :item.ttyy == '0'}">
                  <!-- 	<text v-if="item.ttyy" class="ttyyTextStyle" :class="{'gray-element':item.invalid}">{{item.ttyyText}}</text> -->
                  <view class="dundax"><text class="flex fex-box" v-if="!item.channel"><text
                        class="cuIcon-infofill dundaxText"></text>仅限{{item.scope_channel_label}}使用</text></view>
                  <text class="cu-bar-yhj-left-rule padding-tb-sm point"
                    @click="showMore(item,['fade', 'slide-top'])">详细说明<text class="lg text-gray margin-left-xs inblcok"
                      :class="item.show?'cuIcon-fold':'cuIcon-unfold'"></text></text>
                </view>
                <!--  <uni-transition custom-class="transition"  :mode-class="modeRuleClass" :styles="styles" :duration="100" :show="item.show"> -->
                <view class="rule-con-ul">
                  <view class="rule-con" :class="{activeWy : item.show}">
                    {{item.vdesc}}
                  </view>
                </view>
                <!--  </uni-transition> -->
              </view>
            </view>
          </view>
        </view>
        <view class="flex justify-center">
          <uni-load-more :status="loadStatus" iconType="circle"></uni-load-more>
        </view>
      </scroll-view>
    </view>
   <loading></loading>
  </view>
  <uni-popup ref="pop1" class="uni-propun-con" :safeArea="false">
    <view class="popup-content text-center padding-lr">
      <view class="uni-dialogCon">
        <view class="belivery-title padding-top text-bold text-c0 text-xl ">赠送一张优惠券</view>
        <view class="text-center">
          <view class="mainbox d_ib">
            <view class="mbprice text-center text-bold">
              ¥{{sendPrice}}
            </view>
            <view class="text-lg padding-top">
              VIP专区券
            </view>
          </view>
        </view>
        <view class="popupEmil-btn flex justify-between align-center">
          <view class="mdbtn text-acenter text-ngreen" @click="hidePop">取消</view>
          <button open-type="share" class="mdbtn text-acenter" @click="tapSenAct">赠送</button>
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
  import { ref, reactive, computed } from 'vue'
  import { onLoad, onShow, onHide, onShareAppMessage } from "@dcloudio/uni-app";
  import { mnavTo, showLoading, hideLoading } from '@/utils/helper';
  import { cred_list, cred_list_infos, coupons_qualifications } from '@/api/vmeitime-http/index.js'
  import tabs from '@/components/comtabs/comtabs.vue'
  import mapi from '@/utils/mapi'
  import { takeSaveShare } from '@/utils/public'
  import global from '@/utils/global';

  const totalBackCup = ref(2)
  const isShareAct = ref(false)
  const isloading = ref(false) //是否正在请求数据
  const itemIndex = ref('0')
  const currentIndex = ref('1')
  const pageSize = ref(6)  //页数
  const curPage = ref(1)  //页码
  const total = ref(0)  //总数量
  const ouponsList = ref([]) //劵列表
  const sharCoupId = ref('')  //券id
  const vimage = ref('') //券分享图片
  const isLogin = ref(false)  //是否登录
  const picShar = ref('') //分享标题
  const endTiemData = ref('') //
  const flag = ref(true)
  const tabCur = ref(0)      //订单列表
  const tabsRef = ref()
  const pop1 = ref()
  const sendPrice = ref()
  const modeRuleClass = ref('fade')
  const pageInfo = ref({
    curPage: 1,
    pageSize: 6,
    backCupPage: 2
  })
  const loadedList = ref(false) //是否加载数据
  const loadStatus = ref('noMore')
  const refLoad = ref(false)
  const nowChangeState = ref()
  const tablist = ref([
    {
      orderState: 'all',
      name: "全部"
    }, {
      orderState: '142',
      name: "待使用"
    }, {
      orderState: '146',
      name: "已使用"
    }, {
      orderState: '141',
      name: "失效"
    }
  ])


  // 优惠卷数据

  const tapToUse = (item : any) => {
    if (item.invalid) return
    uni.switchTab({
      url: '/pages/index/menu/menu'
    })
  }
  //点击不同的tab
  // let deepCloneDemo = JSON.parse(JSON.stringify(discountData.value))
  const tabSelect = (item : any, index : any) => {
    nowChangeState.value = item.orderState
    // ouponsList.value = []
    loadList('refeash')
  }


  const showMore = (list : any, type : any) => {
    // if (list.invalid) return
    // console.log('123')
    // 遍历订单数据，找到与当前项匹配的项
    modeRuleClass.value = type
    ouponsList.value.forEach((item) => {
      if (item.cred_conpon_id === list.cred_conpon_id) {
        // 将当前项的menuFlag设置为true
        item.show = !item.show;
        console.log(item.show)
      } else {
        // 将其他项的menuFlag设置为false（或不设置，根据你的需求）
        // item.show = false;
      }
    });

  }
  const hidePop = () => {
    pop1.value?.close()
  }
  const tapSenAct = () => {
    // mnavTo('/pages/user/couponCollection/couponCollection')
    hidePop()
  }
  onShow(() => {
    isLogin.value = uni.getStorageSync(global.IS_LOGIN) || false;
    // console.log('是否登录--------------------------------------------------', isLogin.value)
    // if (!isLogin.value) {
    //   mnavTo(`/pages/login/login`)
    // }
    nowChangeState.value = '142'
    // ouponsList.value = []
    loadList('refeash')
  })

  const refresherrefresh = () => {
    refLoad.value = true
    setTimeout(() => {
      refLoad.value = false
    }, 500)
    loadList('refeash')
  }

  const scrolltolower = () => {
    // console.log('adddddddddddddddddddddddddddddddddddddd')
    loadList('add')
  }
  //订单列表
  const loadList = async (source : any) => {
    loadStatus.value = 'loading'
    if (source == 'refeash') {
      pageInfo.value.curPage = 1
      pageInfo.value.backCupPage = 2
    }
   
    // if (pageInfo.value.curPage > pageInfo.value.backCupPage && source != 'refeash') {
    //   console.log("没有更多啦")
    //   // mapi.msg('没有更多啦')
    //   loadStatus.value = 'noMore'
    //   return
    // }
    console.log('-----------------------------------------',pageInfo.value.curPage,pageInfo.value.pageSize,total.value)
    if (pageInfo.value.curPage > pageInfo.value.backCupPage && source != 'refeash') {
       //mapi.msg('数据加载完毕!!！') total  curPage = 2 * pageSize = 6 >= totalRows = 10 
       loadStatus.value = 'noMore'
       return
    } 
    showLoading()
    try {
		// , smid: '' 
      let res = await cred_list({ curPage: pageInfo.value.curPage, pageSize: pageInfo.value.pageSize, status: nowChangeState.value})
      loadedList.value = true
      if (!res.result) {
        hideLoading()
        if (res.shortMessage == '用户未登录') {
        	mnavTo('/pages/login/login')
        }
        return
      }
     hideLoading()
     if(pageInfo.value.curPage==res.page.totalPage){
     		 loadStatus.value='noMore'
     }else{
     		 loadStatus.value='more'
     }
      pageInfo.value.curPage += 1
      pageInfo.value.backCupPage = res.page.totalPage || 0
      if (source == 'refeash') {
        ouponsList.value = []
      }
      const listData = res.object.map(item => {
        const flagss = item.scope_channel?.split(',').some(j => j.trim() === '1114' ? true : false);
        console.log('flagss--------------------------', flagss)
        return {
          channel: flagss,
          show: false,
          endTime: item.end_date ? item.end_date.split(" ")[0] : '',
          ...item
        }
      })
      total.value = res.page.totalRows
      ouponsList.value = [...ouponsList.value, ...listData]
      // orderData.value = res.object
    } catch (e) {
      hideLoading();
      loadedList.value = false
      //TODO handle the exception
      loadStatus.value = 'noMore'
    }
  }
  // 分享好友
  onShareAppMessage(() => {
    return new Promise(async (resolve, reject) => {
      let param = {
        event_id: '41' || '', //事件id  1:会员注册, 2:H5分享， 3:商品价格标签, 4:商品超链接分享, 5:拼团， 6:线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
        source_type: '1', //1首页分享，2商品分享，3名片分享，4商品超链接分享5拼团,6线下团购,7.总部推广 ,8.VIP专属卡,9.预留1,10.预留2
        goods_id: '',
        goods_sku: '',
        activity_id: '',
        sell_member_id: '16681', //门店id
        credCouponId: sharCoupId.value || ''
        // buy_member_id: paramData.buy_member_id || '', //用户id
      }
      try {
        let shareId = await takeSaveShare(param)
        if (shareId) {
          let msg = {
            title: `特赠您一张${picShar.value}元VIP专区券，请查收`,
            content: '',
            path: '/pages/user/couponCollection/couponCollection?shareId=' + shareId,
            imageUrl: vimage.value
          }
          resolve(msg)
        } else {
          reject('');
          mapi.msg('分享失败,请稍后重试')
        }
      } catch (e) {
        reject('');
        mapi.msg('分享失败,请稍后重试')
        console.error(e)
        //TODO handle the exception
      }

    });
  });
  //获取分享券的详情图片
  const getImg = async (data) => {
    try {
      showLoading()
      let res = await cred_list_infos(data)
      if (res) {
        hideLoading()
        vimage.value = res.object.vimage ? `https://test-cdn-static.yekjx.com/${res.object.vimage}` : '';   //this.$fileUrl线上地址
        picShar.value = res.object.coupon_money || 0
        console.log(res)
      }
    } catch (e) {
      hideLoading();
      mapi.msg('获取失败!');
    }
  }
  //赠送券
  const sendItem = async (item : any) => {
    console.log('send', item);
    endTiemData.value = item.endTime
    if (item.status !== '142') {
      mapi.msg('该券已经使用');
      return
    }
    try {
      showLoading()
      let res = await coupons_qualifications({ credCouponId: item.cred_conpon_id })
      if (res) {
        hideLoading();
        flag.value = res.result
        getImg({ credCouponId: item.cred_conpon_id })
        console.log('是否有发券资格------------------------------------------------------------', flag.value)
      }
    } catch (e) {
      hideLoading();
      mapi.msg('获取数据失败!');
    }
    sendPrice.value = item.coupon_money
    sharCoupId.value = item.cred_conpon_id
    if (flag.value) {
      pop1.value.open()
    } else {
      mapi.msg('服务器暂忙，请稍后尝试');
    }

  }
</script>

<style lang="scss" scoped>
  .emptyActives{
    width: 100% !important;
    padding: 0 !important;
    margin: 0 !important;
  }
  .dundax {
    // position: absolute;
    // left: 220rpx;
    // bottom: 15rpx;
    color: #333;
    font-family: "Microsoft YaHei UI";
    font-size: 26rpx;
    font-weight: 400;

    .fex-box {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 300rpx;
      display: block;
    }

    .dundaxText {
      margin-right: 10rpx;
    }
  }

  .containerBootom {
    padding-bottom: 80rpx;
  }

  .cu-bar-invalid {
    color: #FFF;
    font-size: 24rpx;
    font-weight: 400;
    background-color: #C4C4C4 !important;
    position: absolute;
    width: 45%;
    height: 60rpx;
    justify-content: center;
    align-items: center;
    display: flex;
    transform: rotate(45deg);
    letter-spacing: 4rpx;
    right: -105rpx;
    top: 25rpx;
  }

  .header-con {
    width: 100%;
    position: sticky;
    top: 0;
    background-color: #fff;
    z-index: 9999;
  }

  .coupon-con {
    width: 674.316rpx;
    margin: 30rpx auto;
  }

  .ttyyTextStyle {
    color: #FF6868;
    font-family: "Microsoft YaHei UI";
    font-size: 28rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
  }

  .sr_box {
    @include centBox(152rpx, 44rpx, #EBEFFB);
    color: #7683AA;
    border-radius: 0 8rpx 0 20rpx;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 2;
  }

  .actbox {
    @include centBox(120rpx, 52rpx, #FF6868);
    border-radius: 52rpx;

    &.gry {
      background: #C4C4C4;
    }
  }

  .cu-bar-invalid {
    color: #FFF;
    font-family: "Microsoft YaHei UI";
    font-size: 24rpx;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    background-color: #C4C4C4 !important;
    position: absolute;
    width: 45%;
    height: 60rpx;
    justify-content: center;
    align-items: center;
    display: flex;
    transform: rotate(45deg);
    right: -105rpx;
    top: 25rpx;
  }

  .gray-element {
    filter: grayscale(100%);
  }

  .alreadyClass {
    color: #fff !important;
    background-color: #C4C4C4 !important;
  }

  .gray-color {
    color: #999 !important;
  }

  .uni-bar-wbg {
    .cu-bar-yhj {
      border-radius: 8rpx;
      background: #FFF;
      box-shadow: 0px 0px 10px 0px rgba(212, 219, 238, 0.80);
      // min-height: 180.744rpx;
      display: flex;
      justify-content: space-between;
      margin-bottom: 30rpx;
      align-items: center;
      transition: all .5s;
      overflow: hidden;
      position: relative;

      // &:last-child{
      //   margin-bottom: 0;
      // }
      .cu-bar-yhj-right {
        display: flex;
        align-items: center;
        margin-right: -10rpx;

        .cu-bar-yhj-rightBtn {
          width: 142rpx;
          height: 72rpx;
          border-radius: 36rpx;
          background: #E4F8E4;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 28rpx;
          color: #56BF7A;
        }
      }

      .cu-bar-yhj-left {
        display: flex;
        width: 100%;

        .cu-bar-yhj-left-text {
          justify-content: space-between;
          padding-top: 30rpx;
          margin-left: 20rpx;
          margin-right: 30rpx;
          padding-bottom: 10rpx;
          position: relative;
          display: flex;
          flex-direction: column;
          flex: 1;

          .activeWy {
            transform: translateY(0%) !important;
            opacity: 1 !important;
            height: auto !important;
            transition: all 0.1s ease-out;
          }

          .rule-con-ul {
            overflow: hidden;
          }

          .ruleconulptop {
            padding-top: 20rpx;
          }

          .rule-con {
            width: 100%;
            color: #999;
            // margin-top: 10rpx;
            // font-family: "Microsoft YaHei UI";
            font-size: 24rpx;
            // font-weight: 400;
            // line-height: normal;
            letter-spacing: 0.24px;
            transform: translateY(-120%);
            transition: all .5s;
            height: 0;
            opacity: 0;
            // transform: scale(0);
            // transition: all .5s;
          }

          .ruleActive {
            // height: 100%;
            transform: scale(1);
          }
        }

        .cu-bar-yhj-Pic {
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          min-width: 202rpx;
          border-radius: 4px 0px 0px 4px;
          position: relative;
          // background: url('https://cdn-static.yekjx.com/food/images/car_img08.png');
          // background-repeat: repeat-y;
          background-color: #FFF0F0;
          z-index: 12;

          &::before {
            content: '';
            width: 20rpx;
            height: 100%;
            position: absolute;
            right: -7rpx;
            top: 0;
            background-size: 25rpx 25rpx;
            background-image: radial-gradient(#fff 8rpx, transparent 6rpx);
            background-repeat: repeat-y;
          }
        }

        .cu-bar-yhj-pic-Invalid {
          background-color: #F5F5F5;
        }

        .cu-bar-yhj-PicStyle {
          color: #FF6868;
          font-size: 60rpx;
          font-weight: 700;

          .price_text {
            font-size: 28rpx;
            margin-left: 10rpx;
          }

          .cu-bar-yhj-PicZk {
            font-weight: 400;
            // margin-left: -10rpx;
            font-size: 24rpx;
          }
        }

        .cu-bar-yhj-min {
          color: #FF6868;
          font-size: 24rpx;
          font-weight: 400;
          letter-spacing: 0.24px;
        }

        .cu-bar-yhj-left-text {
          display: flex;
          flex-direction: column;

          .cu-bar-yhj-title {
            color: #333;
            font-size: 32rpx;
            font-weight: 700;
            margin-bottom: 10rpx;
          }

          .cu-bar-yhj-left-time {
            color: #666;
            font-size: 28rpx;
            font-weight: 400;
            margin-top: 10rpx;
          }

          .cu-bar-yhj-left-rule {
            color: #999;
            font-size: 24rpx;
            font-weight: 400;
            display: inline-block;
          }

          .routerHover {
            transform: rotate(180deg);
          }
        }
      }
    }
  }

  // .padding-top-zdy {
  // 	padding-top: 30rpx;
  // }

  .justiftRight {
    justify-content: flex-end !important;
  }

  // pop1-s
  .popup-content {
    background-color: #fff;
    border-radius: 16rpx;
    width: 530rpx;
    padding-bottom: 40rpx;
    flex-shrink: 0;

    .mdbtn {
      width: 202rpx;
      height: 80rpx;
      flex-shrink: 0;
      border-radius: 5px;
      border: 1px solid #5DB175;
      background-color: #fff;

      &:nth-child(2) {
        background-color: #5DB175;
        color: #fff;
      }
    }

    .mainbox {
      width: 450rpx;
      height: 294rpx;
      color: #765320;
      background: url('https://cdn-static.yekjx.com/food/images/coup_zs01.png') no-repeat center/contain;
    }

    .mbprice {
      padding-top: 80rpx;
      font-size: 64rpx;
    }

  }

  // pop1-end
</style>